package com.atguigu.tingshu.album.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void testLock() {
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock", "lock");
        String uuid = UUID.randomUUID().toString();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(flag)) {
            // 加锁成功... 执行业务
            String value = stringRedisTemplate.opsForValue().get("num");
            if (StringUtils.isEmpty(value)) {
                return;
            }
            int num = Integer.parseInt(value);
            stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));

            //4.将锁释放
//            stringRedisTemplate.delete("lock");
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            //设置脚本文本
            String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                    "then\n" +
                    "    return redis.call(\"del\",KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";
            redisScript.setScriptText(script);
            redisScript.setResultType(Long.class);
            stringRedisTemplate.execute(redisScript, List.of("lock"), uuid);
        } else {
            // 加锁失败... 重试
            try {
                Thread.sleep(100);
                testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
